package com.cg.controller;

import com.cg.service.ResumeAnalysisService;
import com.cg.dto.*;
import com.cg.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.concurrent.CompletableFuture;

/**
 * 简历分析控制器
 * 提供简历上传、解析、测评、优化等功能的REST API
 */
@Slf4j
@RestController
@RequestMapping("/resume")
public class ResumeAnalysisController {

    @Autowired
    private ResumeAnalysisService resumeAnalysisService;

    /**
     * 上传并解析PDF简历
     * @param userId 用户ID
     * @param file PDF文件
     * @return 异步任务ID
     */
    @PostMapping("/upload")
    public Result<String> uploadResume(@RequestParam("userId") Long userId,
                                     @RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error("请选择要上传的文件");
            }
            
            if (!file.getOriginalFilename().toLowerCase().endsWith(".pdf")) {
                return Result.error("只支持PDF格式的简历文件");
            }
            
            CompletableFuture<String> future = resumeAnalysisService.uploadAndParseResume(userId, file);
            String taskId = future.get(); // 等待任务创建完成
            
            return Result.success(taskId, "简历上传成功，正在解析中...");
        } catch (Exception e) {
            log.error("简历上传失败: userId={}", userId, e);
            return Result.error("简历上传失败：" + e.getMessage());
        }
    }

    /**
     * 获取简历解析结果
     * @param resumeId 简历ID
     * @return 解析结果
     */
    @GetMapping("/parse-result/{resumeId}")
    public Result<ResumeParseResultDTO> getParseResult(@PathVariable Long resumeId) {
        try {
            ResumeParseResultDTO result = resumeAnalysisService.getResumeParseResult(resumeId);
            if (result == null) {
                return Result.error("简历解析结果不存在");
            }
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取简历解析结果失败: resumeId={}", resumeId, e);
            return Result.error("获取解析结果失败：" + e.getMessage());
        }
    }

    /**
     * 生成测评报告
     * @param userId 用户ID
     * @param resumeId 简历ID
     * @param targetPositionId 目标岗位ID（可选）
     * @return 异步任务ID
     */
    @PostMapping("/evaluation")
    public Result<String> generateEvaluation(@RequestParam("userId") Long userId,
                                           @RequestParam("resumeId") Long resumeId,
                                           @RequestParam(value = "targetPositionId", required = false) Long targetPositionId) {
        try {
            CompletableFuture<String> future = resumeAnalysisService.generateEvaluationReport(userId, resumeId, targetPositionId);
            String taskId = future.get();
            
            return Result.success(taskId, "测评报告生成中...");
        } catch (Exception e) {
            log.error("生成测评报告失败: userId={}, resumeId={}", userId, resumeId, e);
            return Result.error("生成测评报告失败：" + e.getMessage());
        }
    }

    /**
     * 获取测评报告
     * @param reportId 报告ID
     * @return 测评报告
     */
    @GetMapping("/evaluation/{reportId}")
    public Result<EvaluationReportDTO> getEvaluationReport(@PathVariable Long reportId) {
        try {
            EvaluationReportDTO report = resumeAnalysisService.getEvaluationReport(reportId);
            if (report == null) {
                return Result.error("测评报告不存在");
            }
            return Result.success(report);
        } catch (Exception e) {
            log.error("获取测评报告失败: reportId={}", reportId, e);
            return Result.error("获取测评报告失败：" + e.getMessage());
        }
    }

    /**
     * 生成简历优化建议
     * @param userId 用户ID
     * @param resumeId 简历ID
     * @param targetPositionId 目标岗位ID（可选）
     * @return 异步任务ID
     */
    @PostMapping("/optimization")
    public Result<String> generateOptimization(@RequestParam("userId") Long userId,
                                             @RequestParam("resumeId") Long resumeId,
                                             @RequestParam(value = "targetPositionId", required = false) Long targetPositionId) {
        try {
            CompletableFuture<String> future = resumeAnalysisService.generateOptimizationSuggestions(userId, resumeId, targetPositionId);
            String taskId = future.get();
            
            return Result.success(taskId, "优化建议生成中...");
        } catch (Exception e) {
            log.error("生成优化建议失败: userId={}, resumeId={}", userId, resumeId, e);
            return Result.error("生成优化建议失败：" + e.getMessage());
        }
    }

    /**
     * 获取简历优化建议
     * @param optimizationId 优化建议ID
     * @return 优化建议
     */
    @GetMapping("/optimization/{optimizationId}")
    public Result<ResumeOptimizationDTO> getOptimization(@PathVariable Long optimizationId) {
        try {
            ResumeOptimizationDTO optimization = resumeAnalysisService.getOptimizationSuggestions(optimizationId);
            if (optimization == null) {
                return Result.error("优化建议不存在");
            }
            return Result.success(optimization);
        } catch (Exception e) {
            log.error("获取优化建议失败: optimizationId={}", optimizationId, e);
            return Result.error("获取优化建议失败：" + e.getMessage());
        }
    }

    /**
     * 获取AI分析任务状态
     * @param taskId 任务ID
     * @return 任务状态
     */
    @GetMapping("/task-status/{taskId}")
    public Result<AiAnalysisTaskDTO> getTaskStatus(@PathVariable String taskId) {
        try {
            AiAnalysisTaskDTO task = resumeAnalysisService.getTaskStatus(taskId);
            if (task == null) {
                return Result.error("任务不存在");
            }
            return Result.success(task);
        } catch (Exception e) {
            log.error("获取任务状态失败: taskId={}", taskId, e);
            return Result.error("获取任务状态失败：" + e.getMessage());
        }
    }

    /**
     * 使用RAG查询简历相关信息
     * @param resumeId 简历ID
     * @param query 查询问题
     * @return 相关回答
     */
    @PostMapping("/rag-query")
    public Result<String> queryWithRAG(@RequestParam("resumeId") Long resumeId,
                                     @RequestParam("query") String query) {
        try {
            if (query == null || query.trim().isEmpty()) {
                return Result.error("查询问题不能为空");
            }
            
            String answer = resumeAnalysisService.queryResumeWithRAG(resumeId, query.trim());
            return Result.success(answer);
        } catch (Exception e) {
            log.error("RAG查询失败: resumeId={}, query={}", resumeId, query, e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 清理简历解析结果缓存
     * @param resumeId 简历ID
     * @return 操作结果
     */
    @PostMapping("/clear-cache/{resumeId}")
    public Result<String> clearCache(@PathVariable Long resumeId) {
        try {
            resumeAnalysisService.clearResumeParseResultCache(resumeId);
            return Result.success("缓存清理成功");
        } catch (Exception e) {
            log.error("清理缓存失败: resumeId={}", resumeId, e);
            return Result.error("清理缓存失败：" + e.getMessage());
        }
    }

    /**
     * 健康检查接口
     * @return 服务状态
     */
    @GetMapping("/health")
    public Result<String> health() {
        return Result.success("简历分析服务运行正常");
    }

    /**
     * 获取用户最近一次的简历分析概览
     */
    @GetMapping("/latest-by-user/{userId}")
    public Result<java.util.Map<String, Object>> latestByUser(@PathVariable Long userId) {
        try {
            java.util.Map<String, Object> data = resumeAnalysisService.getLatestAnalysisByUser(userId);
            return Result.success(data);
        } catch (Exception e) {
            log.error("获取最近一次分析失败: userId={}", userId, e);
            return Result.error("获取最近一次分析失败：" + e.getMessage());
        }
    }

    /**
     * 获取简历相似度报告
     */
    @GetMapping("/similarity/{resumeId}")
    public Result<com.cg.dto.SimilarityReportDTO> getSimilarityReport(@PathVariable Long resumeId,
                                                                      @RequestParam(value = "topK", required = false) Integer topK,
                                                                      @RequestParam(value = "threshold", required = false) Double threshold) {
        try {
            com.cg.dto.SimilarityReportDTO report = resumeAnalysisService.computeSimilarityReport(resumeId, topK, threshold);
            return Result.success(report);
        } catch (Exception e) {
            log.error("获取相似度报告失败: resumeId={}", resumeId, e);
            return Result.error("相似度报告生成失败：" + e.getMessage());
        }
    }
}